package com.chenyaowei.happyhub.service;

import com.chenyaowei.happyhub.mapper.AdminMapper;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.annotation.Resource;

@Service
public class RegisterService {
    @Resource
    AdminMapper adminMapper;
    String username;
    String password;
    String confirmPassword;
    String email;
    Model model;
    public void setParameters(String username,String password,String confirmPassword,String email,Model model){
        this.username=username;
        this.password=password;
        this.confirmPassword=confirmPassword;
        this.email=email;
        this.model=model;
    }
    public boolean register(){
        if (isUsernameExists()){
            model.addAttribute("registerError","用户名已存在");
            return false;
        }
        else {
            if (isUsernameCorrect()){
                if (isPasswordCorrect()){
                    if (isConfirmPasswordCorrect())
                        return true;
                    else {
                        model.addAttribute("registerError","两次密码不一致");
                        return false;
                    }
                }
                else{
                    model.addAttribute("registerError","密码格式错误，请输入4-20个数字或字母");
                    return false;
                }
            }
            else {
                if (username!=null)
                model.addAttribute("registerError","用户名格式错误，请输入4-20个数字,字母，符号");
                return false;
            }
        }
    }
    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getConfirmPassword() {
        return confirmPassword;
    }

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }

    public String getEmail() {
        return email;
    }

    public boolean isUsernameExists(){
        return adminMapper.selectAdminByUsername(username) != null;
    }
    public boolean isUsernameCorrect(){
       if(username.length() > 20 || username.length() <4 || !isStringCorrect(username))
           return false;
       else
           return true;
    }
    public boolean isConfirmPasswordCorrect(){
        return password.equals(confirmPassword);
    }
    public boolean isPasswordCorrect(){
        if(password.length() > 20 || password.length() <4 || password.contains(" "))
            return false;
        else
            return true;
    }
    public static boolean isStringCorrect(String str){

        for(int i=str.length();--i>=0;){
            int chr=str.charAt(i);
            if(!(chr>=65&&chr<=90)&&!(chr>=97&&chr<=122)&&!(chr>=48&&chr<=57))
                return false;
        }
        return true;
    }
}
